package com.adtec.yxdemo.utils;

import com.jfinal.plugin.activerecord.Record;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class FileLandUtil {
    public static final char WriteAAA = 0x03;

    /**
     * 拿到一个没有内容的file
     *
     * @return
     * @throws IOException
     */
    public static File fileClear(File file) throws IOException {
        if (!file.exists()) {
            file.createNewFile();
        } else {
            FileWriter fileWriter = new FileWriter(file);
            fileWriter.write("");
            fileWriter.flush();
            fileWriter.close();
        }
        return file;
    }

    /**
     * 获取对象的属性并拼接成相应的格式
     *
     * @param record
     * @return
     */
    public static String fileForMat(Record record, String[] filed, StringBuffer sb) {
        for (String s : filed) {
            if (record.get(s) != null&&record.get(s)!="") {
                sb.append(record.get(s).toString()).append(WriteAAA);
            } else {
                sb.append("null").append(WriteAAA);
            }
        }
        return sb.substring(0,sb.length()-1);
    }

    /**
     * 循环将数据库中的数据写入文件
     */
    public static File documentSave(List<Record> records, String path, String[] filed) throws IOException {
        File file = FileLandUtil.fileClear(new File(path));
        FileWriter fileWriter = new FileWriter(file);
        for (int i = 0; i < records.size(); i++) {
            String str = FileLandUtil.fileForMat(records.get(i), filed, new StringBuffer());
            fileWriter.write(str);
            fileWriter.write("\r\n");
        }
        fileWriter.flush();
        fileWriter.close();
        return file;
    }

    /**
     * 标识文件的生成
     *
     * @param indPath
     * @param datFile
     */
    public static void fileSaveFlag(String indPath, File datFile, Integer line) throws IOException {
        BufferedReader bufferedReader=new BufferedReader(new FileReader(datFile));
        String s="";
        StringBuffer stringBuffer=new StringBuffer();
        while ((s=bufferedReader.readLine())!=null){
            stringBuffer.append(s);
        }
        StringBuffer sb = new StringBuffer();
        sb.append(" ").append(line).append(" ").append(stringBuffer.toString().length()).append(" ").append(datFile.length()).append(" ").append(datFile.getPath());
        File file = new File(indPath);
        FileWriter writer = new FileWriter(file);
        writer.write(sb.toString());
        writer.flush();
        writer.close();
    }
    /**
     * 生成文件件名格式
     */
    public static String getDate(){
        Date date=new Date();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMdd");
        return simpleDateFormat.format(date);
    }
}
